﻿using Nx.ViewModels;
#if !NETFX_CORE
using System.Windows;
using System.Windows.Controls;
#else
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
#endif

namespace Nx.Controls
{
    /// <summary>
    /// The ViewModelPresenter control displays views bound to viewModels via the ConfigureVVMMapping extension of IKernel
    /// </summary>
    public class ViewModelPresenter : ContentControl
    {
        public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register(
            "ViewModel",
            typeof(ViewModelBase),
            typeof(ViewModelPresenter),
            new PropertyMetadata(null, ViewModelChanged));

        public ViewModelBase ViewModel
        {
            get
            {
                return (ViewModelBase)this.GetValue(ViewModelProperty);
            }
            set
            {
                this.SetValue(ViewModelProperty, value);
            }
        }

        private static void ViewModelChanged(object sender, DependencyPropertyChangedEventArgs args)
        {
            ViewModelPresenter viewLocator = sender as ViewModelPresenter;
            if (viewLocator != null)
            {
                if (args.OldValue != null)
                {
                    ViewModelBase viewModel = args.OldValue as ViewModelBase;
                    if (viewModel != null)
                    {
                        viewLocator.Content = null;
                    }
                }
                if (args.NewValue != null)
                {
                    ViewModelBase viewModel = args.NewValue as ViewModelBase;
                    if (viewModel != null)
                    {
                        viewLocator.Content = viewModel.View;
                        ((FrameworkElement)viewModel.View).DataContext = viewModel;
                    }
                }
            }
        }
    }
}
